package com.kj.platformlogistics.base;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.transition.Fade;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.kj.platformlogistics.R;
import com.kj.platformlogistics.util.StatusBarUtil;
import com.kj.platformlogistics.util.StringUtils;

import java.util.List;

/**
 * BaseActivity
 */

public abstract class BaseActivity extends AppCompatActivity {
    private Context context;
    private final int TRANSITION_TIME = 1 * 1000;//滑动转场的时间
    public Fade mFadeTransition;//Activity转场效果
    //常量部分 标题栏类型
    protected final int TITLEBAR_NULL = -1, TITLEBAR_DEFAULT = 0,TITLEBAR_RIGHT_IMG = 2;
    /**
     * 沉浸状态栏
     **/
    private boolean isSetStatusBar = true;
    /**
     * 日志输出标志-activity名称
     **/
    protected final String TAG = this.getClass().getSimpleName();

    private LinearLayout parentLinearLayout;
    private ViewGroup _barToolbar; //仅当做 RelativeLayout 来使用
    private ImageView _barBack;
    private TextView _barTitle;
    private TextView _barTvRight;
    private ImageView _barIvRight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCollector.addActivity(this);
        context = this;
        setupWindowAnimation();//5.0以上的动画
        setSteepStatusBar(false);
        setStatusBar(false);
        init(savedInstanceState);
        switch (getTitleBarType()) {
            case TITLEBAR_NULL://无标题栏

                break;
            case TITLEBAR_DEFAULT:
                initContentView(R.layout.layout_toolbar_default);
                this._barToolbar = findViewById(R.id._barToolbar);
                this._barBack = findViewById(R.id._barBack);
                this._barTitle = findViewById(R.id._barTitle);
                this._barTvRight = findViewById(R.id._barTvRight);
                break;
            case TITLEBAR_RIGHT_IMG:
                initContentView(R.layout.layout_toolbar_img_click);
                this._barToolbar = findViewById(R.id._barToolbar);
                this._barBack = findViewById(R.id._barBack);
                this._barTitle = findViewById(R.id._barTitle);
                this._barIvRight = findViewById(R.id._barIvRight);
                break;
        }
        setContentView(setLayoutResourceID());
        //初始化控件
        initView();
    }
    public Context getContext() {
        return context;
    }

    /**
     * 设置页面切换动画
     */
    private void setupWindowAnimation() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mFadeTransition = new Fade();
                mFadeTransition.setDuration(TRANSITION_TIME);
                getWindow().setEnterTransition(mFadeTransition);
                getWindow().setExitTransition(mFadeTransition);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置沉浸状态栏
     * 如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明
     * 这样半透明+白=灰, 状态栏的文字能看得清
     *
     * @param isSetStatusBar
     */
    public void setSteepStatusBar(boolean isSetStatusBar) {
        this.isSetStatusBar = isSetStatusBar;
    }

    protected void setStatusBar(boolean isdark) {
        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        StatusBarUtil.setRootViewFitsSystemWindows(this, isdark);
        //设置状态栏透明
        StatusBarUtil.setTranslucentStatus(this);
        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (isSetStatusBar && !StatusBarUtil.setStatusBarDarkTheme(this, true)) {
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtil.setStatusBarColor(this, 0x55000000);
        }
    }

    /**
     * 自定义 toolbar 布局 加入到 viewgroup
     *
     * @param layoutResID
     */
    private void initContentView(@LayoutRes int layoutResID) {
        try {
            ViewGroup viewGroup = findViewById(android.R.id.content);
            viewGroup.removeAllViews();
            parentLinearLayout = new LinearLayout(this);
            parentLinearLayout.setOrientation(LinearLayout.VERTICAL);
            viewGroup.addView(parentLinearLayout);
            //  add the layout of BaseActivity in parentLinearLayout
            LayoutInflater.from(this).inflate(layoutResID, parentLinearLayout, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 重写该方法 用来使 子 Activity 复用 toolbar
     *
     * @param layoutResID
     */
    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        //  added the sub-activity layout id in parentLinearLayout
        if (parentLinearLayout == null) {
            super.setContentView(layoutResID);
        } else {
            LayoutInflater.from(this).inflate(layoutResID, parentLinearLayout, true);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    protected abstract void init(Bundle savedInstanceState);

    protected abstract int setLayoutResourceID();

    protected abstract void initView();

    protected abstract void initData();

    /**
     * 获取要使用的标题栏样式(此函数由子类重写)
     *
     * @return
     */
    protected abstract int getTitleBarType();

    /**
     * 标题栏后退按钮点击事件 在xml中调用
     *
     * @param v
     */
    public void onTitleBarBackBtnClick(View v) {
        this.finish();//结束当前Activity，并退出窗口
    }

    /**
     * 标题栏右侧按钮点击事件(此方法可被子类重写，以响应右上角按钮点击事件)--TITLEBAR_RIGHT
     *
     * @param v
     */
    public void onTitleBarRightClick(View v) {

    }

    /**
     * 修改状态栏颜色
     *
     * @param colorId
     */
    protected void setStatusBarColor(@ColorRes int colorId) {
        StatusBarUtil.setStatusBarColor(this, colorId);
    }

    /**
     * 修改状态栏文字颜色
     *
     * @param isdark true 黑色  false白色
     */
    protected void setAndroidNativeLightStatusBar(boolean isdark) {
        StatusBarUtil.setStatusBarDarkTheme(this, isdark);
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                Glide.with(this).resumeRequests();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置数据
        initData();
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                Glide.with(this).pauseRequests();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 点击手机上的返回键，返回上一层
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
            ActivityCollector.removeActivity(this);
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * [页面跳转]
     *
     * @param clz
     */
    public void startActivity(Class<?> clz) {
        startActivity(new Intent(BaseActivity.this, clz));
    }

    /**
     * [携带数据的页面跳转]
     *
     * @param clz
     * @param bundle
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * [含有Bundle通过Class打开编辑界面]
     *
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public void startActivityForResult(Class<?> cls, Bundle bundle,
                                       int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 1.使用getSupportFragmentManager().getFragments()获取到当前Activity中添加的Fragment集合
         * 2.遍历Fragment集合，手动调用在当前Activity中的Fragment中的onActivityResult()方法。
         */
        if (getSupportFragmentManager().getFragments() != null && getSupportFragmentManager().getFragments().size() > 0) {
            List<Fragment> fragments = getSupportFragmentManager().getFragments();
            for (Fragment mFragment : fragments) {
                mFragment.onActivityResult(requestCode, resultCode, data);
            }
        }

    }

    /**
     * 设置标题
     *
     * @param text
     */
    public void setTitleText(@StringRes int text) {
        try {
            _barTitle.setText(getString(text));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置标题
     *
     * @param text
     */
    public void setTitleText(@Nullable String text) {
        try {
            if (StringUtils.isEmpty(text))
                text = "";
            _barTitle.setText(text);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置标题背景颜色
     *
     * @param
     */
    public void setTitleBackColor(@ColorRes int colorRes) {
        try {
            _barToolbar.setBackgroundColor(ContextCompat.getColor(this, colorRes));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置标题字体颜色
     *
     * @param colorRes
     */
    public void setTitleFontColor(@ColorRes int colorRes) {
        try {
            _barTitle.setTextColor(ContextCompat.getColor(this, colorRes));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置右侧文字
     *
     * @param text
     */
    public void setRightText(@Nullable String text) {
        try {
            if (StringUtils.isEmpty(text))
                text = "";
            _barTvRight.setText(text);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置右侧文字
     *
     * @param text
     */
    public void setRightText(@StringRes int text) {
        try {
            _barTvRight.setText(getString(text));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置右侧文字颜色
     *
     * @param colorRes
     */
    public void setRightFontColor(@ColorRes int colorRes) {
        try {
            _barTvRight.setTextColor(ContextCompat.getColor(this, colorRes));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * TITLEBAR_RIGHT = 2，设置右侧图标
     *
     * @param resId
     */
    public void setRightImg(@DrawableRes int resId) {
        try {
            _barIvRight.setImageResource(resId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * TITLEBAR_RIGHT = 2，设置右侧图标
     */
    public ImageView getRightImg() {
        return _barIvRight;
    }

    /**
     * _barIvRight 设置右侧图标显示状态
     */
    public void setRightImgVisible(boolean isVisible) {
        try {
            if (isVisible) {
                _barIvRight.setVisibility(View.VISIBLE);
            } else {
                _barIvRight.setVisibility(View.INVISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * _barBack 设置返回键显示状态
     */
    public void setBackVisible(boolean backVisible) {
        try {
            if (backVisible) {
                _barBack.setVisibility(View.VISIBLE);
            } else {
                _barBack.setVisibility(View.INVISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * _barTvRight 是否显示
     */
    public void setTvRightVisible(boolean isVisible) {
        try {
            if (isVisible) {
                _barTvRight.setVisibility(View.VISIBLE);
            } else {
                _barTvRight.setVisibility(View.INVISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
